package com.ndood.admin.service.user.impl;

import java.util.Date;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ndood.admin.core.constaints.AdminErrCode;
import com.ndood.admin.core.exception.AdminException;
import com.ndood.admin.pojo.system.StaffPo;
import com.ndood.admin.pojo.system.dto.StaffDto;
import com.ndood.admin.repository.system.StaffRepository;
import com.ndood.admin.service.user.AccountInfoService;
import com.ndood.common.base.util.JPAUtil;

@Service
public class AccountInfoServiceImpl implements AccountInfoService{

	@Autowired
	private StaffRepository userDao;
	
	@Override
	public StaffDto getAccountInfoById(String userId) throws Exception {
		if(StringUtils.isBlank(userId)) {
			throw new AdminException(AdminErrCode.ERR_OTHER,"用户不存在！");
		}
		Optional<StaffPo> option = userDao.findById(Integer.parseInt(userId));
		if(!option.isPresent()) {
			throw new AdminException(AdminErrCode.ERR_OTHER,"用户不存在！");
		}
		
		StaffPo po = option.get();
		StaffDto dto = new StaffDto();
		JPAUtil.fatherToChild(po, dto);
		
		// 不能暴露密码
		dto.setPassword(null);
		return dto;
	}

	@Override
	public void updateAccountInfo(StaffDto dto) throws Exception {
		dto.setPassword(null);
		dto.setMobile(null);
		dto.setEmail(null);
		dto.setUpdateTime(new Date());
		
		StaffPo po = userDao.findById(dto.getId()).get();
		JPAUtil.childToFather(dto, po);
		
		// Step2: 更新时间
		userDao.save(po);
	}
	
}
